package org.jeecg.modules.CheckTask.controller;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.gson.JsonObject;
import org.jeecg.modules.CheckTask.entity.CheckTask;
import org.jeecg.modules.CheckTask.entity.CheckTaskDetail;
import org.jeecg.modules.CheckTask.service.ICheckTaskDetailService;
import org.jeecg.modules.CheckTask.service.ICheckTaskService;
import org.jeecg.modules.CheckTask.vo.CheckTaskPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;


/**
 * @Description: 排查任务表
 * @Author: jeecg-boot
 * @Date:   2023-02-21
 * @Version: V1.0
 */
@Api(tags="排查任务表")
@RestController
@RequestMapping("/CheckTask/checkTask")
@Slf4j
public class CheckTaskController {
	@Autowired
	private ICheckTaskService checkTaskService;
	@Autowired
	private ICheckTaskDetailService checkTaskDetailService;
	
	/**
	 * 排查任务管理分页列表查询
	 *
	 * @param checkTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "排查任务表-分页列表查询")
	@ApiOperation(value="排查任务表-分页列表查询", notes="排查任务表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CheckTask>> queryPageList(CheckTask checkTask,
												  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												  HttpServletRequest req) {
		QueryWrapper<CheckTask> queryWrapper = QueryGenerator.initQueryWrapper(checkTask, req.getParameterMap());
		Page<CheckTask> page = new Page<CheckTask>(pageNo, pageSize);
		IPage<CheckTask> pageList = checkTaskService.page(page, queryWrapper);
		List<CheckTask> collect = pageList.getRecords().stream().filter(c -> !c.getState().equals("2")).collect(Collectors.toList());
		pageList.setRecords(collect);
		return Result.OK(pageList);
	}


	/**
	 * 排查任务记录分页列表查询
	 *
	 * @param checkTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "排查任务表-分页列表查询")
	@ApiOperation(value="排查任务表-分页列表查询", notes="排查任务表-分页列表查询")
	@GetMapping(value = "/listRecord")
	public Result<IPage<CheckTask>> listRecord(CheckTask checkTask,
												  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												  HttpServletRequest req) {
		checkTask.setState("2");
		QueryWrapper<CheckTask> queryWrapper = QueryGenerator.initQueryWrapper(checkTask, req.getParameterMap());
		Page<CheckTask> page = new Page<CheckTask>(pageNo, pageSize);
		IPage<CheckTask> pageList = checkTaskService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	
	/**
	 *   添加
	 *
	 * @param checkTaskPage
	 * @return
	 */
	@AutoLog(value = "排查任务表-添加")
	@ApiOperation(value="排查任务表-添加", notes="排查任务表-添加")
    //@RequiresPermissions("CheckTask:tt_check_task:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CheckTaskPage checkTaskPage) {
		CheckTask checkTask = new CheckTask();
		BeanUtils.copyProperties(checkTaskPage, checkTask);
		checkTaskService.saveMain(checkTask, checkTaskPage.getCheckTaskDetailList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param checkTaskPage
	 * @return
	 */
	@AutoLog(value = "排查任务表-编辑")
	@ApiOperation(value="排查任务表-编辑", notes="排查任务表-编辑")
    //@RequiresPermissions("CheckTask:tt_check_task:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CheckTaskPage checkTaskPage) {
		CheckTask checkTask = new CheckTask();
		BeanUtils.copyProperties(checkTaskPage, checkTask);
		CheckTask checkTaskEntity = checkTaskService.getById(checkTask.getId());
		if(checkTaskEntity==null) {
			return Result.error("未找到对应数据");
		}
		checkTaskService.updateMain(checkTask, checkTaskPage.getCheckTaskDetailList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "排查任务表-通过id删除")
	@ApiOperation(value="排查任务表-通过id删除", notes="排查任务表-通过id删除")
    //@RequiresPermissions("CheckTask:tt_check_task:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		checkTaskService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "排查任务表-批量删除")
	@ApiOperation(value="排查任务表-批量删除", notes="排查任务表-批量删除")
    //@RequiresPermissions("CheckTask:tt_check_task:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.checkTaskService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "排查任务表-通过id查询")
	@ApiOperation(value="排查任务表-通过id查询", notes="排查任务表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CheckTask> queryById(@RequestParam(name="id",required=true) String id) {
		CheckTask checkTask = checkTaskService.getById(id);
		if(checkTask==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(checkTask);

	}

	/*--------------------------------子表处理-排查任务明细表-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "排查任务明细表-通过主表ID查询")
	@ApiOperation(value="排查任务明细表-通过主表ID查询", notes="排查任务明细表-通过主表ID查询")
	@GetMapping(value = "/listCheckTaskDetailByMainId")
	public Result<IPage<CheckTaskDetail>> listTtCheckTaskDetailByMainId(CheckTaskDetail ttCheckTaskDetail,
																		  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
																		  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
																		  HttpServletRequest req) {
		QueryWrapper<CheckTaskDetail> queryWrapper = QueryGenerator.initQueryWrapper(ttCheckTaskDetail, req.getParameterMap());
		Page<CheckTaskDetail> page = new Page<CheckTaskDetail>(pageNo, pageSize);
		IPage<CheckTaskDetail> pageList = checkTaskDetailService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param checkTask
    */
    //@RequiresPermissions("CheckTask:tt_check_task:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CheckTask checkTask) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<CheckTask> queryWrapper = QueryGenerator.initQueryWrapper(checkTask, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<CheckTask> checkTaskList = checkTaskService.list(queryWrapper);

      // Step.3 组装pageList
      List<CheckTaskPage> pageList = new ArrayList<CheckTaskPage>();
      for (CheckTask main : checkTaskList) {
          CheckTaskPage vo = new CheckTaskPage();
          BeanUtils.copyProperties(main, vo);
          List<CheckTaskDetail> checkTaskDetailList = checkTaskDetailService.selectByMainId(main.getId());
          vo.setCheckTaskDetailList(checkTaskDetailList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "排查任务表列表");
      mv.addObject(NormalExcelConstants.CLASS, CheckTaskPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("排查任务表数据", "导出人:"+sysUser.getRealname(), "排查任务表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("CheckTask:tt_check_task:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<CheckTaskPage> list = ExcelImportUtil.importExcel(file.getInputStream(), CheckTaskPage.class, params);
              for (CheckTaskPage page : list) {
                  CheckTask po = new CheckTask();
                  BeanUtils.copyProperties(page, po);
                  checkTaskService.saveMain(po, page.getCheckTaskDetailList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }


	@RequestMapping(value = "/submitTaskDetail")
	public Result<String> submitTaskDetail(String data) {
		CheckTaskDetail checkTaskDetail = JSONObject.parseObject(data, CheckTaskDetail.class);
		checkTaskDetail.setRectiftState("0");
		checkTaskDetailService.updateById(checkTaskDetail);
		checkTaskService.update(null,new LambdaUpdateWrapper<CheckTask>()
				.set(CheckTask::getState,"1")
				.eq(CheckTask::getId,checkTaskDetail.getTaskId()));
		return Result.OK("提交成功!");
	}

	@RequestMapping(value = "/completeTaskDetail")
	public Result<String> completeTaskDetail(String data) {
		CheckTaskDetail checkTaskDetail = JSONObject.parseObject(data, CheckTaskDetail.class);
		checkTaskDetailService.updateById(checkTaskDetail);
		checkTaskService.update(null,new LambdaUpdateWrapper<CheckTask>()
				.set(CheckTask::getState,"1")
				.eq(CheckTask::getId,checkTaskDetail.getTaskId()));
		return Result.OK("操作成功!");
	}

	@RequestMapping(value = "/completeTask")
	public Result<String> completeTask(String id) {

		List<CheckTaskDetail> checkTaskDetails = checkTaskDetailService.selectByMainId(id);
		List<CheckTaskDetail> details = checkTaskDetails.stream().filter(c -> c.getHandleResult() == null).collect(Collectors.toList());
		System.out.println(checkTaskDetails);
		if (details.size()==0) {
			checkTaskService.update(null,new LambdaUpdateWrapper<CheckTask>()
					.set(CheckTask::getState,"2")
					.eq(CheckTask::getId,id));
		}else {
			return Result.OK("请先完成此计划下所有隐患项目！");
		}

		return Result.OK("操作成功");
	}

	@RequestMapping("appSubmitTaskDetail")
	public Result<String> appSubmitTaskDetail(String data) {
		CheckTaskDetail checkTaskDetail = JSONObject.parseObject(data, CheckTaskDetail.class);

		return  checkTaskDetailService.appSubmitTaskDetail(checkTaskDetail);

	}

	@RequestMapping("appGetCheckTaskDetail")
	public Result<List<CheckTaskDetail>> appGetCheckTaskDetail(String data){
		CheckTaskDetail checkTaskDetail = JSONObject.parseObject(data, CheckTaskDetail.class);
		return checkTaskDetailService.appGetCheckTaskDetail(checkTaskDetail);

	}

}
